package com.yc.litemonitoring.client;

import com.yc.api.HostInfo;
import com.yc.util.HostInfoCollector;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

/**
 * @program: lite_monitoring
 * @description:
 * @author: zy
 * @create: 2025-03-19 21:45
 */
public class LiteMonitoringClientHandler extends
        SimpleChannelInboundHandler<Object> {
    private static final Logger logger =
            LoggerFactory.getLogger(LiteMonitoringClientHandler.class);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object obj)
            throws Exception {
        // NOOP
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel ch = ctx.channel(); // 获取通道
        //启动一个定时任务，每5秒向服务端发送一次数据
        ch.eventLoop().scheduleAtFixedRate(
                new Runnable() {
                    @Override
                    public void run() {

                        // 获取主机性能信息
                        HostInfo hostInfo = null;
                        try {
                            hostInfo = HostInfoCollector.getHostInfo();
                        } catch (InterruptedException e) {
                            logger.error("error: {}", e);
                        }
                        ch.write(hostInfo);
                        ch.flush();

                        logger.info("调度一次任务，数据：{}", hostInfo);
                    }
                }, 5, 5, TimeUnit.SECONDS);
    }
}
